package map.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;


public class ResourceUtils {
	public static final Logger LOGGER = Logger.getLogger(ResourceUtils.class.getName());
	
	public static Properties loadResource(String fileName) {
		return loadResource(fileName, null);
	}
	
	public static Properties loadResource(String fileName, ClassLoader loader) {
		Properties props = new Properties();
		if (fileName == null || fileName.equals("")) {
			throw new IllegalArgumentException("null reference: " + fileName);
		}
		if (fileName.startsWith("/")) {
			fileName = fileName.substring(1);
		}

		InputStream inStream = null;
		try {
			if (loader == null) {
				loader = ClassLoader.getSystemClassLoader();
			}

			inStream = loader.getResourceAsStream(fileName);
			props.load(inStream);

		} catch (IOException ioe) {
			LOGGER.log(Level.WARNING, ioe.getMessage());
			ioe.printStackTrace();
		}
		return props;
	}
	
	public static String getPropertyAsString(String fileName) {		
		return getPropertyAsString( loadResource(fileName, null) );		
	}
	
	public static String getPropertyAsString(String fileName, ClassLoader loader) {		
		return getPropertyAsString( loadResource(fileName, loader) );		
	}
	
	public static String getPropertyAsString(Properties p) {
		StringWriter writer = new StringWriter();
		p.list(new PrintWriter(writer));
		
		String s = writer.getBuffer().toString();
		
		if (s.contains("-- listing properties --")) {
			s = s.replace("-- listing properties --", "");
		}
		if (s.startsWith("\r\n")) {
			s = s.replaceFirst("\r\n", "");
		}
		
		return s;
	}

}
